<template>
  <div class="item-select-wrapper">
    <div
      class="input-wrapper"
      @click.stop="selecting = !selecting"
      :class="{ borderBlue: selecting }"
    >
      <p :class="{ colorDark: Boolean(item) }">{{ item || placeholder }}</p>
      <i class="iconfont icon-arrow-down" :class="{ colorBlue: selecting }"></i>
    </div>

    <ul class="item-list" :class="{ fadeOut: !selecting }">
      <li v-for="(item, idx) in items" :key="idx" @click="selectItem(idx)">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useEventListener } from '@vueuse/core'

const props = defineProps<{
  items: string[]
  values: string[]
  placeholder: string
  item: string | number | boolean
  value: string | number | boolean
}>()

const emit = defineEmits<{
  (e: 'selectItem', value: string): void
}>()

let selecting = ref(false)

function selectItem(idx: number) {
  if (props.values.length) emit('selectItem', props.values[idx])
  else emit('selectItem', props.items[idx])
}

useEventListener(document, 'click', () => {
  selecting.value = false
})
</script>

<style lang="scss" scoped>
$w: $itemSelectWidth;
$h: $itemSelectHeight;
$fs: $itemSelectFontsize;

.item-select-wrapper {
  box-sizing: border-box;
  width: $w;
  height: $h;

  .input-wrapper {
    width: $w;
    height: $h;

    border-radius: calc($w * 0.01);
    border: 1px solid var(--gray);

    p {
      box-sizing: border-box;
      width: $w;
      height: $h;
      padding-left: $fs;
      line-height: $h;
      color: var(--gray);
      font-size: $fs;

      &:hover {
        cursor: pointer;
      }
    }

    i {
      position: absolute;
      top: 50%;
      right: 5%;
      transform: translateY(-50%);
    }
  }

  .borderBlue {
    border-color: var(--blue);
  }

  .item-list {
    position: absolute;
    z-index: 1;
    top: 120%;
    width: 100%;

    max-height: calc($h * 5);
    overflow-y: auto;

    border-radius: calc($h * 0.1);
    background-color: white;
    box-shadow: 0 0 10px 0.2px var(--gray);

    transition: 0.1s;

    li {
      height: $h;
      padding-left: 10%;
      line-height: $h;

      color: var(--dark);
      font-size: calc($fs * 0.8);

      &:hover {
        background-color: var(--lightGray);
        cursor: pointer;
      }
    }
  }
}
</style>
